<template>
<vp-dialog ref="importDialog" :span="1">
    <template #title>
        <vp-label zh="导入" en="Import" />
    </template>
    <div style="display: flex;flex-wrap: wrap;" v-loading="loading">
        <el-upload action="" :before-upload="beforeUpload" :show-file-list="false">
            <el-button size="medium" type="primary" class="mr-20">
                <vp-label zh="上传" en="Upload" />
                <SvgIcon name="ele-Upload"></SvgIcon>
            </el-button>
        </el-upload>
        <vp-btn type="text" style="margin-left:50px" @click="downloadTemplate">
            <vp-label zh="下载模板" en="Download Template" />
        </vp-btn>
    </div>
</vp-dialog>
</template>
<script setup lang="ts" name="vpImportDialog">
import { reactive, ref } from 'vue';
import request from '/@/utils/request';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';
import axios from 'axios';

const emits = defineEmits(['finish']);

const state = reactive({
    key: '',
    url:"",
    templateName:"",
});
const loading = ref(false);
const importDialog = ref();
const formRef = ref();

const handleOpen = (param: any)=>{
    state.key = param.key;
    state.url = param.url;
    state.templateName = param.templateName;
    importDialog.value.handleOpen();
}

const beforeUpload = (file: any) => {
    if (file) {
        let submitData = new FormData();
        submitData.append('excelFile', file);
        loading.value = true;
        request.post(state.url, submitData, { headers: { 'content-type': 'multipart/form-data' } }).then(res => {
            if(res.data.success === false){
                ElMessage.error({
                    message: res.data.message,
                    dangerouslyUseHTMLString: true,
                    customClass:'max-zindex'
                })
            }else{
                    ElMessage.success({
                    message: res.data.message,
                    customClass:'max-zindex'
                })
                emits("finish", res.data);
                importDialog.value.handleClose();
            }
            loading.value = false;
        })
    }
    return false;
};

const downloadTemplate = ()=>{
    if(state.key){
            const instance = axios.create({
            baseURL: import.meta.env.VITE_API_URL as any, // url = base url + request url
            withCredentials: true, // send cookies when cross-domain requests
            // timeout: 5000, // request timeout
            responseType: 'blob',
            headers: {
                'Content-type': 'application/json',
                token: `${Session.get('token')}`
            }
        });

        instance({
            method: 'get',
            url: `/file/downloadTemplate/${state.key}`
        }).then(res => {
            const content = res.data;
            const blob = new Blob([content]); //构造一个blob对象来处理数据
            const fileName =  state.templateName;
            //对于<a>标签，只有 Firefox 和 Chrome（内核） 支持 download 属性
            //IE10以上支持blob但是依然不支持download
            if ('download' in document.createElement('a')) {
                //支持a标签download的浏览器
                const link = document.createElement('a'); //创建a标签
                link.download = fileName; //a标签添加属性
                link.style.display = 'none';
                link.href = URL.createObjectURL(blob);
                document.body.appendChild(link);
                link.click(); //执行下载
                URL.revokeObjectURL(link.href); //释放url
                document.body.removeChild(link); //释放标签
            } else {
                //其他浏览器
                navigator.msSaveBlob(blob, fileName);
            }

        })
    }
}

defineExpose({
    handleOpen
})
</script>
